package com.xbongbong.paas.help.menu;

import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.pro.domain.entity.AppModuleEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.menu.pojo.dto.CompanyMenuInitDTO;
import com.xbongbong.pro.menu.pojo.dto.MenuInitDTO;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.AppModuleModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/4/16 14:25
 * @since v1.0
 */
@Component
public class CompanyInitMenuHelp {

    private static final Logger LOG = LoggerFactory.getLogger(CompanyInitMenuHelp.class);

    @Resource
    private PaasAppModel paasAppModel;
    @Resource
    private AppModuleModel appModuleModel;
    @Resource
    private InitMenuHelp initMenuHelp;
    @Resource
    private PaasRedisHelper paasRedisHelper;

    public void initMenu(CompanyMenuInitDTO companyMenuInitDTO) throws XbbException {
        try {
            // 判断是否跳过重复提交校验
            if (!Boolean.TRUE.equals(companyMenuInitDTO.getIgnoreConCheck())) {
                //重复提交校验
                if (!paasRedisHelper.checkConcurrentLock(companyMenuInitDTO)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100003);
                }
            }
            String alias = XbbRefTypeEnum.CRM.getAlias();
            String corpid = companyMenuInitDTO.getCorpid();
            PaasAppEntity paasAppEntity = paasAppModel.getByAlias(alias, corpid);
            if (Objects.isNull(paasAppEntity)) {
                AppModuleEntity appModuleEntity = appModuleModel.getByAlias(alias);
                if (Objects.nonNull(appModuleEntity)) {
                    MenuInitDTO menuInitDTO = new MenuInitDTO();
                    BeanUtil.copyProperties(companyMenuInitDTO, menuInitDTO);
                    BeanUtil.copyProperties(appModuleEntity, menuInitDTO);
                    menuInitDTO.setCompanyInit(1);
                    // 根据配置随机选取一些公司使用镜像
                    boolean isUseMirror = initMenuHelp.isUseMirror();
                    if (isUseMirror) {
                        initMenuHelp.simpleCrmInit(menuInitDTO);
                    } else {
                        initMenuHelp.menuInit(menuInitDTO);
                    }
                }
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("初始化方法调用出错：", e);
        }
    }

}
